<?php

namespace common\pay\pay;

use Yii;
use common\components\WeChatFactory;
use common\components\WeChatPayment;
use common\models\OrderModel;

class WeixinPay extends \common\pay\Pay{


    /**
     * 生成待支付订单
     * @param $orderSn
     * @param $price
     * @param $desc
     * @param $options
     * @return array
     * @throws \EasyWeChat\Kernel\Exceptions\InvalidConfigException
     */
    public function prePay($order, $options = [])
    {
        $params = [
            'body'          => $order['subject'],
            'out_trade_no'  => $order['order_sn'],
            'total_fee'     => bcmul($order['price'], 100, 0),
            'trade_type'    => 'JSAPI',
        ];
        $params = array_merge($params, $options);
        $payApp = WeChatFactory::sharePayment();
        $result = $payApp->order->unify($params);
        Yii::info($result, __METHOD__);
        $attributes = [];
        if($result['return_code'] == 'SUCCESS' && $result['result_code'] == 'SUCCESS'
            && !empty($result['prepay_id'])){
            $attributes['package'] = "prepay_id={$result['prepay_id']}";
            OrderModel::updateAll(['prepay_id' => $result['prepay_id']], ['order_sn' => $order['order_sn']]);
        }
        if(!$attributes){
            return $attributes;
        }

        $data = WeChatPayment::generatePrePay($attributes);
        $data['openid']   = $params['openid'];
        $data['price']    = $order['price'];
        $data['order_sn'] = $order['order_sn'];
        $data['order_id'] = $order['orde_id'];
        $data['pay_succ_url'] = Yii::$app->params['pay_succ_url'];
        return $data;
    }

    public function payCallback($notifyData)
    {
        // TODO: Implement pay() method.
    }

    public function refundCallback($notifyData)
    {
        // TODO: Implement refund() method.
    }

    public function settlementCallback($notifyData)
    {
        // TODO: Implement settleMent() method.
    }
}